package com.Ele_Demo.jackiez;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;

import com.Ele_Demo.jackiez.util.LogUtil;

public class Ele_Demo extends Activity {
    private EditText user_name;
    private EditText user_password;
    
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
		//TelephonyManager phoneMgr=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
		//LogUtil.LogShow("[Ele_Demo]", phoneMgr.getLine1Number(), LogUtil.DEBUG);
		//LogUtil.LogShow("[Ele_Demo]", Build.VERSION.SDK, LogUtil.DEBUG);
        user_name = (EditText)findViewById(R.id.username);
        user_password = (EditText)findViewById(R.id.password);
        Button btn_commit = (Button)findViewById(R.id.usercommit);
        btn_commit.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View v){
        		//Intent intent = new Intent(Ele_Demo.this,Ele_Demo_Main.class);
        		//Intent.setClass(Ele_Demo.this,Ele_Demo_Main.class);
        		//Intent intent = new Intent();
        		//intent.setClass(Ele_Demo.this,TabTest.class);
        		//TabHost tabhost = ((TabActivity)getParent()).getTabHost();
        		//processInternetLogin(user_name.getText().toString(),user_password.getText().toString())
        		int i=1;
        		if(processInternetLogin(user_name.getText().toString(),user_password.getText().toString())){
        	    LogUtil.LogShow("[Ele_Demo]", "login successed!", LogUtil.DEBUG);
        	    Editor passwdfile = getSharedPreferences("USERPATH", 0).edit();
        	    passwdfile.putString("USERPATH",user_name.getText().toString());
        	    passwdfile.commit();
        		Intent intent = new Intent();
        		intent.setClass(Ele_Demo.this,Ele_Demo_Main.class);
        		startActivity(intent);
        		Ele_Demo.this.finish();
        		}
        		else{
        			Toast.makeText(getApplicationContext(), "Login Failed! Please Retry...", Toast.LENGTH_LONG).show();
        		}
        	}
        });
    }
    
    private boolean processInternetLogin(String strUID, String strUPW)
    {
      
      String uriAPI = "http://android.wuliu800.com/login.php";
      //String uriAPI = "http://android.wuliu800.com/?file=user&act=login";

      String strRet = "";
      
      try
      {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        HttpPost httpost = new HttpPost(uriAPI);
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("username", strUID)); 
        nvps.add(new BasicNameValuePair("userpass", strUPW)); 
        //LogUtil.LogShow("[Ele_Demo]", "name is "+strUID, LogUtil.DEBUG);
        //LogUtil.LogShow("[Ele_Demo]", "pwd is "+strUPW, LogUtil.DEBUG);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));   
        response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        //LogUtil.LogShow("[Ele_Demo]", "HTTP POST getStatusLine: " + response.getStatusLine(), LogUtil.DEBUG);       
        /* HTML POST response BODY */
        strRet = EntityUtils.toString(entity);
        LogUtil.LogShow("[Ele_Demo]", "The strRet is "+strRet, LogUtil.DEBUG);

        strRet = strRet.trim().toLowerCase();
        
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (entity != null)
        {
          entity.consumeContent();
        }
        LogUtil.LogShow("[Ele_Demo]", "HTTP POST Initialize of cookies.", LogUtil.DEBUG);

        cookies = httpclient.getCookieStore().getCookies(); 
        if (cookies.isEmpty())
        {
            LogUtil.LogShow("[Ele_Demo]", "HTTP POST Cookie not found.", LogUtil.DEBUG);
            LogUtil.LogShow("[Ele_Demo]", entity.toString(), LogUtil.DEBUG);
        }
        else
        {
          for (int i = 0; i < cookies.size(); i++)
          {
              LogUtil.LogShow("[Ele_Demo]", "HTTP POST Found Cookie: " + cookies.get(i).toString(), LogUtil.DEBUG);
          } 
        }
        
        
        if(strRet.equals("y"))
        {
            LogUtil.LogShow("[Ele_Demo]", "YES", LogUtil.DEBUG);
          return true;
        }
        else
        {
            LogUtil.LogShow("[Ele_Demo]", "NO", LogUtil.DEBUG);
          return false;
        }
      }
      catch(Exception e)
      {
        e.printStackTrace();
        return false;
      }
    }
    
}